<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">用户管理</div>
          <el-input
            v-model="classSearchInput"
            placeholder="请输入姓名"
            style="width: 150px"
            class="className"
          ></el-input>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleRecycleUserAll" link class="addmsgbtn" v-if="showRecycle">
           还原
          </el-button>
          <img src="../../assets/images/back.png" class="delimg" @click="backUser" v-if="showRecycle">
      
          <el-button type="primary" @click="handleRecycle" link class="addmsgbtn" v-if="!showRecycle">
            回收站
          </el-button>

          <img src="../../assets/images/加号.png" class="addmsg" @click="handleAdd" v-if="!showRecycle"/>
          <img src="../../assets/images/删除.png" class="delimg" @click="delSelect" alt="" v-if="!showRecycle" />
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" v-if="!showRecycle">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column prop="userName" label="姓名" align="center" />
        <el-table-column prop="department" label="部门" align="center" />
        <el-table-column prop="sex" label="性别" align="center" />
        <el-table-column prop="tel" label="电话" align="center" />
        <el-table-column prop="roleName" label="职能" align="center" >
          <template #header>
            <el-select 
              v-model="selectedRoleId" 
              placeholder="全部职能" 
              clearable
              @change="handleRoleFilter"
              style="width: 120px"
              class="selector"
            >
            <el-option
              :key="0"
              label="全部职能"
              :value="0"
                />
              <el-option
                v-for="option in roleOptions1"
                :key="option.roleId"
                :label="option.roleName"
                :value="option.roleId"
              />
            </el-select>
          </template>
          </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <el-button link type="success" @click="() => handleEdit(scoped.row)">修改</el-button>
            <el-button link type="primary" @click="handleReset(scoped.row)">重置</el-button>
            <el-button link type="danger" @click="delRow(scoped.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="recycleData" style="width: 100%" @selection-change="handleSelectionChangeUser" v-if="showRecycle">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column prop="userName" label="姓名" align="center" />
        <el-table-column prop="department" label="部门" align="center" />
        <el-table-column prop="sex" label="性别" align="center" />
        <el-table-column prop="tel" label="电话" align="center" />
        <el-table-column prop="roleName" label="职能" align="center" >
          <template #header>
            <el-select 
              v-model="selectedRoleId" 
              placeholder="全部职能" 
              clearable
              @change="handleRoleFilter"
              style="width: 120px"
            >
            <el-option
              :key="0"
              label="全部职能"
              :value="0"
                />
              <el-option
                v-for="option in roleOptions1"
                :key="option.roleId"
                :label="option.roleName"
                :value="option.roleId"
              />
            </el-select>
          </template>
          </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <el-button link type="success" @click="() => handleRecycleUser(scoped.row)">还原</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page" v-if="!showRecycle">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentPageChange"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
        </div>

      </div>
      <div class="page" v-if="showRecycle">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total1"
          :current-page="currentPage1"
          :page-size="pageSize1"
          @current-change="handleCurrentPageChange1"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize1"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange1"
            />条
      </div>

      </div>
    </div>

    <!-- 添加用户 -->
    <el-dialog v-model="dialogVisible" title="添加用户" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="formData.userName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="部门">
            <el-select v-model="formData.departmentId" placeholder="请选择部门">
              <el-option
                v-for="(option, index) in departmentOptions"
                :key="index"
                :label="option.departmentName"
                :value="option.departmentId"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" placeholder="请选择性别">
              <el-option value="男" label="男" />
              <el-option value="女" label="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="职能" prop="roleId">
            <el-select v-model="formData.roleId" placeholder="请选择职能">
              <!-- 遍历roleOptions -->
              <el-option v-for="(option, index) in roleOptions" :key="index" :label="option.roleName" :value="option.roleId" :disabled="option.roleId=='1'||option.roleId=='4'"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="账号" prop="account">
            <el-input v-model="formData.account" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="formData.tel" placeholder="请输入电话" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog v-model="dialogVisible2" title="修改用户" width="400px" :show-close="false">
      <el-form
        :model="formData2"
        :rules="rules2"
        ref="formRef2"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="formData2.userName" placeholder="请输入姓名" />
          </el-form-item>
           <el-form-item label="部门">
            <el-select v-model="formData2.departmentId" placeholder="请选择部门">
              <el-option
                v-for="(option,index) in departmentOptions"
                :key="index"
                :label="option.departmentName"
                :value="option.departmentId"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData2.sex" placeholder="请选择性别">
              <el-option value="男" label="男" />
              <el-option value="女" label="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="职能" prop="roleId">
            <el-select v-model="formData2.roleId" placeholder="请选择职能" >
                 <!-- 遍历roleOptions -->
              <el-option v-for="(option, index) in roleOptions" :key="index" :label="option.roleName" :value="option.roleId" :disabled="option.roleId=='1' || option.roleId=='4'" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="账号" prop="account">
            <el-input v-model="formData2.account" disabled />
          </el-form-item>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="formData2.tel" />
          </el-form-item>
        </el-row>
        <!-- <el-row>
          <el-form-item label="密码" prop="password">
           <el-button type="primary" @click="resetPassword">重置密码</el-button>
          </el-form-item>
        </el-row> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible2 = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleEdit1" class="confirm">修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, addUser, getDepartmentList,getUserById,updateUser,deleteUser,getRoleList,getRecycleList,recoverUser} from '../api/User.js'

// 数据
const tableData = ref([])
// 搜索内容
const classSearchInput = ref('')
// 分页
const currentPage = ref(1) // 当前页码
const pageSize = ref(7) // 每页显示的数量
const total = ref(0) // 总记录数

const currentPage1 = ref(1) // 当前页码
const pageSize1 = ref(7) // 每页显示的数量
const total1 = ref(0) // 总记录数
//职能id
const selectedRoleId = ref(0)


//职能不包括学生和超级管理员数组
const roleOptions = ref([])
//职能不包超级管理员数组
const roleOptions1 = ref([])

//是否显示回收站
const showRecycle = ref(false)

//回收站数据
const recycleData = ref([])

//还原选中的用户ID数组
const selectedUserIds = ref([])

//用户列表接口
function fetchData() {
  let data = {
    pageIndex: currentPage.value, // 当前页码
    pageSize: pageSize.value, // 每页显示的数量
    search: classSearchInput.value, // 搜索内容
    roleId: selectedRoleId.value, // 选中的角色ID
  }
  getUserList('userList', data).then((res) => {
    if (res.code === 200) {
      
      tableData.value = res.dataset.userList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}
// 部门列表接口
const departmentOptions = ref([])
function fetchDepartmentList() {
  let data = {
    search: '', // 搜索内容
  }
  getDepartmentList('departmentList', data).then((res) => {
    if (res.code === 200) {
  
      departmentOptions.value = res.dataset.departmentList
     
    }
  })
}

// 角色列表接口
function fetchRoleList() {
  let data = {}
  getRoleList('roleList', data).then((res) => {
    if (res.code === 200) {
      
      roleOptions.value = res.dataset
      // //过滤出roleId为1和4的角色
      roleOptions1.value =  res.dataset.filter((item) => item.roleId!= 1)
    }
  })
}

//获取回收站接口
function fetchRecycleList(){
  let data = {
    pageIndex: currentPage1.value, // 当前页码
    pageSize: pageSize1.value, // 每页显示的数量
    userName: classSearchInput.value, // 搜索内容
    roleId: selectedRoleId.value, // 选中的角色ID
  }
  getRecycleList('recycleBinList', data).then((res) => {
    if (res.code === 200) {
      
      recycleData.value = res.dataset.recycleBinList
      total1.value = res.dataset.pageCount * pageSize1.value
    }
  })
}

//用户还原接口
function fetchRecycleUser(userId){
  recoverUser('updateDelFlag',userId).then((res) => {
    if (res.code === 200) {
      fetchRecycleList()
      ElMessage.success('还原成功')
    }
  })
}


// 初始化时加载数据
onMounted(() => {
  fetchData()
  fetchRoleList()
})

//页码改变
const handleCurrentPageChange = (val) => {
  currentPage.value = val
  fetchData() // 重新加载数据
}
//职能表头该改变
function handleRoleFilter() {
  if (showRecycle.value) {
    currentPage1.value = 1; // 重置页码为第一页
    fetchRecycleList(); // 重新加载数据
  }else{
    currentPage.value = 1; // 重置页码为第一页
    fetchData() // 重新加载数据
  }
}

//还原分页改变
function handleCurrentPageChange1(val) {
  currentPage1.value = val
  fetchRecycleList() // 重新加载数据
}
// 搜索
const handleSearch = () => {
  if(showRecycle.value){
    currentPage1.value = 1; // 重置页码为第一页
    fetchRecycleList()
  }else{
    currentPage.value = 1; // 重置页码为第一页
    fetchData() // 重新加载数据
  }
}

//点击回收站
function handleRecycle(){
  showRecycle.value = true;
  fetchRecycleList();
}

//点击返回
function backUser(){
  showRecycle.value = false;
  fetchData()
}
//还原选中的用户发生变化
const handleSelectionChangeUser = (val) => {
  selectedUserIds.value = val.map(row => row.userId) 
 
  
}

//点击还原批量
function handleRecycleUserAll(){
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning('请先勾选要还原的行')
    return
  }else{
    ElMessageBox.confirm('确认要还原选中的用户嘛？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      
      fetchRecycleUser(selectedUserIds.value)
      selectedUserIds.value = []; // 清空选中的用户ID数组
    }).catch(() => {
      ElMessage.info('已取消还原')
    })
  }
}

//点击还原
function handleRecycleUser(row){
  ElMessageBox.confirm('确认要还原行吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    
    
    fetchRecycleUser([row.userId])
  }).catch(() => {
    ElMessage.info('已取消还原')
  })
}


//删除用户接口
function deleteUserInfo(arr){
  let data = {
    userIds: arr,
  } 
  deleteUser("deleteUser",data).then((res) => {
    if (res.code === 200) {
      fetchData(classSearchInput.value) 
    }
  })
}

// 删除
const delRow = (row) => {
  ElMessageBox.confirm('确认要删除行吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning', 
  }).then(() => {
    const userIds = [row.userId]; 
  
    deleteUserInfo(userIds); // 调用删除用户的接口 
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
// 删除：选中的行
const selectedRows = ref([])
const handleSelectionChange = (val) => {
  selectedRows.value = val
}
const delSelect = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先勾选要删除的行')
    return
  }
  ElMessageBox.confirm('确认要删除选中的行吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const selectedIds = selectedRows.value.map((row) => row.userId)
      deleteUserInfo(selectedIds)
      // 清空选中的行
      selectedRows.value = []
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 添加用户模态框
// 新增：模态框显示状态
const dialogVisible = ref(false)
// 新增：表单数据
const formData = ref({
  userName: '',
  department: '',
  sex: '',
  tel: '',
  roleId: '',
  account: '',
  password: '123456',
  departmentId: '',
})

// 新增：表单引用
const formRef = ref(null)
// 新增：表单验证规则
const rules = ref({
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  tel: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的 11 位电话号码',
      trigger: 'blur',
    },
  ],
  roleId: [{ required: true, message: '请选择职能', trigger: 'change' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
//添加用户接口
function addUserInfo() {
  let data = {
    userName: formData.value.userName,
    department: departmentOptions.value.find((item) => item.departmentId === formData.value.departmentId).departmentName,
    sex: formData.value.sex,
    tel: formData.value.tel,
    roleId: formData.value.roleId,
    account: formData.value.account.trim(),
    password: formData.value.password.trim(),
    departmentId: formData.value.departmentId,
  }
  addUser('addUser', data).then((res) => {
    if (res.code === 200) {
      ElMessage.success('添加成功')
      dialogVisible.value = false
      fetchData()
    }else{
      ElMessage.error("手机号或账号已存在")
    }
  })
}
// 新增：点击添加班级按钮方法
const handleAdd = () => {
    fetchDepartmentList()
    formData.value = {
    userName: '',
    department: '',
    sex: '', 
    tel: '',
    roleId: '',
    account: '',
    password: '123456',
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }

  dialogVisible.value = true
}

// 新增：点击确认按钮方法
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证通过，执行添加操作
      addUserInfo()
      dialogVisible.value = false
    } else {
      // 验证失败
      ElMessage.warning('表单验证不通过，请检查输入项')
    }
  })
}




const oldformData2 = ref({})

//根据id获取用户信息接口
function getUserInfo(userId){
  let data = {
    userId,
  }  
  getUserById("userById",data).then((res) => {
      if (res.code === 200) {
        
        formData2.value = res.dataset;
        oldformData2.value = JSON.parse(JSON.stringify(res.dataset));
       
      }
  })
}


// 修改班级模态框
// 修改：模态框显示状态
const dialogVisible2 = ref(false)
// 修改：表单数据
const formData2 = ref({
  userName: '',
  department: '',
  sex: '',
  tel: '',
  roleId: '',
  account: '',
  password: '',
  departmentId: '',
})
// 修改：表单引用
const formRef2 = ref(null)
// 修改：表单验证规则
const rules2 = ref({
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  tel: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的 11 位电话号码',
      trigger: 'blur',
    },
  ],
  roleId: [{ required: true, message: '请选择职能', trigger: 'change' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
})
// 修改：点击修改按钮方法
const handleEdit = (row) => {

     fetchDepartmentList()

  // 填充表单数据

  //调用根据id获取用户信息接口
  getUserInfo(row.userId)
 
  dialogVisible2.value = true
}
//点击重置密码
function resetPassword(){
  ElMessageBox.confirm('确认要重置密码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning', 
  }).then(() => {
    // 用户点击确定，执行重置密码操作
    formData2.value.password = '123456' // 重置密码为 '123456'
    ElMessage.success('密码已重置为 123456') 
  }).catch(() => {
    // 用户点击取消，不执行操作
    ElMessage.info('已取消重置密码')
  })
}

//修改用户信息接口
function updateUserInfo(){
  let data = {
    account: formData2.value.account,
    userId: formData2.value.userId,
  }
  if(formData2.value.roleId!==oldformData2.value.roleId){
    data.roleId = formData2.value.roleId
  }
  if(formData2.value.sex!==oldformData2.value.sex){
    data.sex = formData2.value.sex
  }
  if(formData2.value.userName!==oldformData2.value.userName){
    data.userName = formData2.value.userName
  }
  if(formData2.value.tel !==oldformData2.value.tel){
    data.tel = formData2.value.tel
    if(formData2.value.roleId =='4'){
      ElMessage.success(`手机号已修改，账号更新为：stu_${formData2.value.tel}，密码已重置为123456`);
    }
  

  }
  if(formData2.value.departmentId){
    data.departmentId = formData2.value.departmentId
    data.department = departmentOptions.value.find((item) => item.departmentId === formData2.value.departmentId).departmentName
  }
  if(formData2.value.password){
    data.password = formData2.value.password 
  }
  updateUser("updateUser",data).then((res) => {
    if (res.code === 200) {
   
      ElMessage.success('修改成功')
      dialogVisible2.value = false
      fetchData()
    }
  })
}

// 修改：点击确认按钮方法
const handleEdit1 = () => {
  // 提交表单逻辑
  ElMessageBox.confirm('确认要修改该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning', 
  }).then(() => {
    // 用户点击确定，执行修改操作
    updateUserInfo() 
    dialogVisible2.value = false
  }).catch(() => {
    // 用户点击取消，不执行操作
    ElMessage.info('已取消修改')
  })
  
}

function handleChange(){
  currentPage.value = 1; // 重置页码为第一页
  fetchData()
}

function handleChange1(){
  currentPage1.value = 1; // 重置页码为第一页
  fetchRecycleList()
}


//点击重置
const handleReset = (row) => {
  ElMessageBox.confirm('确认要将密码重置为123456吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    handleReset1(row)
    
  }).catch(() => {
    ElMessage.info('已取消重置')
  })
}

//重置函数
function handleReset1(row){
  let data ={
    userId: row.userId,
    password: '123456',
  }
  updateUser("updateUser",data).then((res) => {
    if (res.code === 200) {
      ElMessage.success('重置成功')
      fetchData()
    }
  })
}

</script>

<style scoped>
:deep(.selector .el-select__wrapper){
  border-radius: 12px !important;
}
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}
/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}
:deep(.className .el-input__wrapper){
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.addmsgbtn{
  margin-right: 20px;
  font-size: 15px;
}

/* 加号 */
.addmsg {
  width: 25px;
  height: 25px;
  margin-right: 20px;
}
/* 垃圾桶 */
.delimg {
  width: 25px;
  height: 25px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
</style>